package com.ruoyi.kjy.controller;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

//import cn.easyes.core.biz.PageInfo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.MyMesssage;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.kjy.config.FanoutExchangeDemoConfig;
import com.ruoyi.kjy.domain.Achievement;
import com.ruoyi.kjy.service.IAchievementService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
//import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.kjy.domain.Demand;
import com.ruoyi.kjy.service.IDemandService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;

/**
 * 需求Controller
 *
 * @author ruoyi
 * @date 2023-04-06
 */
@Api(tags = "需求")
@RestController
@RequestMapping("/demand")
public class DemandController extends BaseController {
    @Autowired
    private IDemandService demandService;
    @Autowired
    private RemoteUserService remoteUserService;
//    @Resource
//    private AmqpTemplate amqpTemplate;
    @Autowired
    private IAchievementService achievementService;

    /**
     * 查询需求列表
     */
//    @GetMapping("/list")
//    public TableDataInfo list(Demand demand) {
//        startPage();
//        QueryWrapper<Demand> queryWrapper = new QueryWrapper<>();
//        queryWrapper.setEntity(demand);
//        List<Demand> list = demandService.list(queryWrapper);
//        return getDataTable(list);
//    }
    @GetMapping("/list")
    public AjaxResult list(Integer current, Integer size, Demand demand) {
        if (Objects.isNull(current)) {
            current = 1;
        }
        if (Objects.isNull(size)) {
            size = 10;
        }
        if (size >= 20) {
            size = 20;
        }
        return AjaxResult.success(demandService.page(current, size, demand));
    }

    /**
     * 导出需求列表
     */
    @Log(title = "需求", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Demand demand) {
        QueryWrapper<Demand> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(demand);
        List<Demand> list = demandService.list(queryWrapper);
        ExcelUtil<Demand> util = new ExcelUtil<Demand>(Demand.class);
        util.exportExcel(response, list, "需求数据");
    }

    /**
     * 获取需求详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Demand byId = demandService.getById(id);
        R<SysUser> userinfoById = remoteUserService.getUserinfoById(byId.getAuthor(), SecurityConstants.INNER);
        byId.setUser(userinfoById.getData());
        return success(byId);
    }

    /**
     * 新增需求
     */
    @Log(title = "需求", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Demand demand) {
        demand.setAuthor(SecurityUtils.getLoginUser().getUserid());
        String nickName = SecurityUtils.getLoginUser().getSysUser().getNickName();
        if (nickName==null) {
            throw new ServiceException("用户昵称为空");
        }
        demand.setAuthorName(nickName);
        demand.setAuthorName(SecurityUtils.getUsername());
        demand.setReleaseTime(new Date());
        demand.setState(0);
        boolean save = demandService.save(demand);
        //推送部分
        AjaxResult ajaxResult = recommendDemand(String.valueOf(demand.getId()));
        List<Achievement> data = (List<Achievement>) ajaxResult.get("data");
        if(data == null || data.isEmpty()){//推荐内容为空就不推荐
            return toAjax(save);
        }
        HashMap<String, Object> stringObjectsHashMap = new HashMap<>();
        ArrayList<Object> idsList = new ArrayList<>();
        for (Achievement datum : data) {
            HashMap<String, String> tHashMap = new HashMap<>();
            tHashMap.put("id",datum.getId().toString());
            tHashMap.put("title", datum.getTitle());
            idsList.add(tHashMap);
        }
        stringObjectsHashMap.put("ids",idsList);
        stringObjectsHashMap.put("type",1);
        MyMesssage myMesssage = new MyMesssage();
        myMesssage.setUid(String.valueOf(SecurityUtils.getUserId()));
        myMesssage.setMsg(JSON.toJSONString(stringObjectsHashMap));
        myMesssage.setCmd("system");
        //amqpTemplate.convertAndSend(FanoutExchangeDemoConfig.EXCHANGE_NAME, "", myMesssage);
        return toAjax(save);
    }

    @ApiOperation("点击进入需求详情，推荐相同的需求")
    @GetMapping("/recommend")
    public AjaxResult recommend(String demandId) {
        Demand byId = demandService.getById(demandId);
        Integer current = 1;
        Integer size = 10;
        String title = byId.getTitle();
        Demand demand = new Demand();
        // 只推荐状态为已审核的数据
        demand.setState(1);
        demand.setSearchWord(title);
        IPage<Demand> page = demandService.page(current, size, demand);
        List<Demand> list = page.getRecords();
        for (Demand demand1 : list) {
            if (demandId.equals(String.valueOf(demand1.getId()))){
                list.remove(demand1);
                break;
            }
        }
        return AjaxResult.success(page);
    }


    @ApiOperation("发布需求，推送成果")
    @GetMapping("/recommendDemand")
    public AjaxResult recommendDemand(String DemandId) {
        Demand byId = demandService.getById(DemandId);
        Integer current = 1;
        Integer size = 10;
        String title = byId.getTitle();
        Achievement achievement = new Achievement();
        // 只推荐状态为已审核的数据
        achievement.setState(1);
        achievement.setSearchWord(title);
        IPage<Achievement> espage = achievementService.page(current, size, achievement);
        return AjaxResult.success(espage.getRecords());
    }

    /**
     * 修改需求
     */
    @Log(title = "需求", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Demand demand) {
//        demand.setAuthorName(SecurityUtils.getUsername());
        String createBy = demand.getCreateBy();
        String username = SecurityUtils.getUsername();
//        if (createBy.equals(username)) {
//            demand.setState(0);
//            return warn("不可审核自己添加的需求");
//        }
        return toAjax(demandService.updateById(demand));
    }

    @InnerAuth
    @PostMapping("/updateNickName")
    public AjaxResult updateNickName(@RequestBody SysUser user) {
        Demand demand = new Demand();
        demand.setAuthor(user.getUserId());
        demand.setAuthorName(user.getNickName());
        demandService.updateNickName(demand);
        return AjaxResult.success();
    }

    /**
     * 删除需求
     */
    @Log(title = "需求", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(demandService.removeByIds(ids));
    }
}
